package top.ajun.mall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.mall.product.dao.BrandDao;
import top.ajun.mall.product.entity.BrandEntity;
import top.ajun.mall.product.service.BrandService;
import top.ajun.mall.product.service.CategoryBrandRelationService;

import java.util.Map;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> wrapper = Wrappers.lambdaQuery();
        if (!StrUtil.isEmpty(key)) {
            wrapper.eq(BrandEntity::getBrandId, key).or().like(BrandEntity::getName, key);
        }
        return new PageUtils(page(new Query<BrandEntity>().getPage(params), wrapper));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段数据一致
        this.updateById(brand);
        if (StrUtil.isNotEmpty(brand.getName())) {
            // 如果要更新品牌名称，则关联表中也需要进行级联更新
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());

            // TODO 更新其它关联的品牌信息
        }
    }

}